
//$(function () { plusReady(); })

var _sellerInfo;
function plusReady() {
    var scancode = getUrlParam("code");
    //var scancode = "03F2";
    //console.log(scancode);
    getSellerInfo(scancode);

    $("#btnpay").on("click", function () {
        // 数据为空
        if (!$("#password").val() || !$("#payamount").val()) { return; }
        if (!_sellerInfo) { return; }
        $("#password").val("");

        commitorder();
    });
}

if (window.plus) {
    plusReady();
} else {
    document.addEventListener('plusready', plusReady, false);
}

// 获取收款者信息
function getSellerInfo(scancode) {
    // 根据Code获取用信息
    $.ajax({
        type: "GET", url: configManager.RequstUrl + "api/user/profile?code=" + scancode
    }).done(function (data) {
        if ("success" != data.state) {
            console.log(data.message);
        }
        var scanuser = data.data;
        if (!scanuser) { plus.nativeUI.alert("不存在该用户！"); return; }

        _sellerInfo = scanuser;

        $("#userpic").attr("src", configManager.avatarImgurl.format(scanuser.avatar_id, "50-50"));
        $("#username").html("<p>收款：" + scanuser.name + "</p>");
    });
}

// 生成一个临时订单号
function commitorder() {
    var currentloginuser = JSON.parse(plus.storage.getItem(storageManager.user));
    var amount = $("#payamount").val().trim();
    var postorder = { "userid": currentloginuser.id, "token": currentloginuser.token, "seller": _sellerInfo.id, "amount": amount, "payment": 1 };

    // 如果对方是商家
    if (_sellerInfo.store) { postorder["store"] = _sellerInfo.store.id; }

    // 提交订单
    $.ajax({
        type: "POST",
        url: configManager.RequstUrl + "api/order/create",
        async: true,
        data: postorder
    }).done(function (data) {
        if ("success" != data.state) { console.log(data.message); plus.nativeUI.alert(data.message); return; }

        var postpay = { "userid": currentloginuser.id, "token": currentloginuser.token, "order": data.data.id };
        // 确认支付
        $.ajax({
            type: "POST",
            url: configManager.RequstUrl + "api/order/pay",
            data: postpay
        }).done(function (pdata) {
            if ("success" != pdata.state) { console.log(data.message); plus.nativeUI.alert(data.message); return; }
          
          plus.ui.alert("付款成功！");
	      clicked("../mine/wallet/income.html?t=all");
        });
        
        

    });
}
